//
//  SQLiteDataBaseManager.m
//  18-SQLite
//
//  Created by dllo on 16/8/8.
//  Copyright © 2016年 ZHW. All rights reserved.
//

#import "SQLiteDataBaseManager.h"
#import "Contact.h"
@implementation SQLiteDataBaseManager
+ (SQLiteDataBaseManager *)shareManager {
    static SQLiteDataBaseManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SQLiteDataBaseManager alloc] init];
    });
    return manager;
}

- (BOOL)openSQLite3 {
    NSArray *pathArray =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document = [pathArray firstObject];
    
    NSString *dbPath = [document stringByAppendingPathComponent:@"contact.db"];
    
    NSLog(@"%@", dbPath);
    BOOL isOpen = YES;
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"打开数据库成功");
        isOpen = YES;
    } else {
        NSLog(@"打开失败错误为%d", result);
        isOpen = NO;
    }
    return isOpen;
}

- (BOOL)closeSQLite3 {
    int result = sqlite3_close(dbPoint);
    return [self isOperationResult:result alertText:@"关闭"];
}

- (BOOL)creatTable {
    NSString *creatSQL = @"CREATE TABLE IF NOT EXIST contact1 (contact_name TEXT, contact_address TEXT, contact_telNumber INT PRIMARY KEY)";
    int result = sqlite3_exec(dbPoint, [creatSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"创建表"];
    // 删除表
    // drop table 表名
}

- (BOOL)insertContact:(Contact *)contact {
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO contact1 (contact_name, contact_address, contact_telNumber) VALUES ('%@', '%@', %ld);", contact.name, contact.address, contact.telNumber];
    // 自增字段 autoincrement
    // 默认如果填入null 值会从1开始
    // 如果填入其他值 会从其他值开始 例:填入110 从110开始计算
    int result = sqlite3_exec(dbPoint, [insertSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"插入数据"];
    return YES;
}

- (BOOL)deleteContact:(Contact *)contact {
    NSString *deleteSQL = [NSString stringWithFormat:@"DELETE FROM stu1 WHERE contact_telNumber=%ld", contact.telNumber];
    int result = sqlite3_exec(dbPoint, [deleteSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"删除"];
    return YES;
}

- (BOOL)deleteAll {
    NSString *deleteAllSQL = @"DELETE FROM stu1 WHERE 1=1";
    int result = sqlite3_exec(dbPoint, [deleteAllSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"删除全部"];
}

- (BOOL)updateOldName:(NSString *)oldName newName:(NSString *)newName {
    // UPDATE 表名 set 字段名 = 新值 WHERE 字段名 = 旧值
    NSString *updateSQL = [NSString stringWithFormat:@"UPDATE stu1 SET stu_name = '%@' WHERE stu_name = '%@'", newName, oldName];
    int result = sqlite3_exec(dbPoint, [updateSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"更新数据"];
}

- (__kindof NSArray *)selectAll {
    NSString *selectAll = @"SELECT * FROM contact1";
    sqlite3_stmt *stmt = NULL;

    int result = sqlite3_prepare(dbPoint, [selectAll UTF8String], -1, &stmt, NULL);
    NSMutableArray *array = [NSMutableArray array];
    if (result == SQLITE_OK) {
     
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            // 取出第0列的数据 根据类型选择函数
            const unsigned char *contact_name = sqlite3_column_text(stmt, 0);
            // 取出第1列的数据, 根据类型选择函数
            const unsigned char *contact_address = sqlite3_column_text(stmt, 1);
            int contact_contactInfo = sqlite3_column_int(stmt, 2);
//            const unsigned char *contact_imagePath = sqlite3_column_text(stmt, 3);

            Contact *contact = [[Contact alloc] init];
            contact.name = [NSString stringWithUTF8String:(const char *)contact_name];
            contact.address = [NSString stringWithUTF8String:(const char *)contact_address];
            contact.telNumber = contact_contactInfo;
//            contact.imagePath = [NSString stringWithUTF8String:(const char *)contact_imagePath];
            [array addObject:contact];
        }
    }
    // 循环结束后 销毁替身
    sqlite3_finalize(stmt);
    return array;
}

- (BOOL)isOperationResult:(int)result alertText:(NSString *)text {
    BOOL isOperation = YES;
    if (result == SQLITE_OK) {
        NSLog(@"%@成功", text);
        isOperation = YES;
    } else {
        NSLog(@"%@失败错误为%d", text, result);
        isOperation = NO;
    }
    return isOperation;
}

@end
